<template>
<div>
	<!--添加任务dialog-->
	<el-dialog :title="action+'子任务'" :visible.sync="taskInputVisible">
		<taskInput @saveSubTask="saveSubTask" :taskForm="subTaskForm"></taskInput>
	</el-dialog>

	<!--显示任务详情dailog-->
	<el-dialog :title="subTaskForm.title" :visible.sync="taskDetailVisible">
		<taskDetail :task="subTaskForm"></taskDetail>
	</el-dialog>

	<!--项目流程大概情况-->
	<el-row style="margin-bottom: 10px;">
		<el-col :span="6">
			<span style="color:#7a838f;">项目名称:</span><span>{{project.project_name}}</span>
		</el-col>
		<el-col :span="4">
			<el-dropdown size="small">
			  <span class="el-dropdown-link">
			    所有流程<i class="el-icon-arrow-down el-icon--right"></i>
			  </span>
			  <el-dropdown-menu slot="dropdown">
			    <el-dropdown-item
			    	v-for="(flow,index) in flows"
			    	:key="index">{{flow.ch_name}} - <span :style="'color: '+flow.status.color+';'">{{flow.status.text}}</span></el-dropdown-item>
			  </el-dropdown-menu>
			</el-dropdown>
		</el-col>
		<el-col :span="4">
			<span style="color:#7a838f;">总工时</span>
			<span style="font-size: 20px">{{project_duration}}</span>
			<span style="color:#7a838f;">天</span>
		</el-col>

		<el-col :span="6">
			<i class="fa fa-circle wait"></i><span style="color:#7a838f;"> {{subtask_summary.wait}} 未进行</span>
			<span style="margin: 0px 20px;">
				<i class="fa fa-circle run"></i><span style="color:#7a838f;"> {{subtask_summary.run}} 进行中</span>
			</span>
			<i class="fa fa-circle finish"></i><span style="color:#7a838f;"> {{subtask_summary.finish}} 已完成</span>
			
			<!--<el-button type="primary" size="mini" icon="el-icon-edit" plain @click="editFlow" v-if="!isInit">编辑流程</el-button>
			<el-button type="primary" size="mini" icon="el-icon-close" plain @click="noEditFlow" v-if="isInit">取消编辑</el-button>-->
		</el-col>
		<el-col :span="4" style="text-align: right;">
			<el-button size="mini" type="info" @click="collapse">展开/收缩</el-button>
		</el-col>
	</el-row>

	<!--如果没有进行流程-->
	<div v-if="isInit">
		<el-card>
			<div slot="header" class="clearfix">
		    <span>流程初始化</span>
		    <el-button style="float: right;" type="primary" size="mini" @click="initFlow">开始初始化</el-button>
		  </div>
		  <el-steps direction="vertical">
		    <el-step :title="flow.ch_name" v-for="(flow,index) in flows" :key="index">
		    	<template slot="description">
		    		<div style="padding: 20px 50px 50px;color: black;width: 100%;">
		    			<el-col :lg="12">
		    				<span>流程时间</span>
			    			<el-date-picker
						      v-model="flow.date_range"
						      type="daterange"
						      size="small"
						      range-separator="至"
						      format="yyyy年MM月dd日"
						      start-placeholder="开始日期"
						      end-placeholder="结束日期"
						      @change="getDuration(index)">
						    </el-date-picker>
		    			</el-col>
		    			<el-col :lg="4">
		    				<span style="color:#7a838f;">需要工时</span>
		    				<span style="font-size: 20px">{{flow.duration}}</span>
		    				<span style="color:#7a838f;">天</span>
		    			</el-col>
		    			<el-col :lg="4">
		    				<span>流程状态:</span>
		    				<el-tag size="small" type="success" v-if="flow.status=='run'">正在进行</el-tag>
		    				<el-tag size="small" type="success" v-else-if="flow.status=='finish'">已经完成</el-tag>
		    				<el-tag size="small" type="info" v-else>等待进行</el-tag>
		    			</el-col>
		    			<el-col :lg="4">
		    				<span style="color:#7a838f;">距离开工还有</span>
		    				<span style="font-size: 20px">{{flow.to_start}}</span>
		    				<span style="color:#7a838f;">天</span>
		    			</el-col>
		    		</div>
		    	</template>
		    </el-step>
		  </el-steps>
		</el-card>
	</div>

	<!--流程实例任务展示-->
	<el-card class="box-card" v-for="(flow,index) in flowInsts" :key="index" v-else>
	  <div slot="header" class="clearfix">
	  	<el-row>
	  		<el-col :lg="4">
	  			<el-tag  size="mini" type="danger" v-if="flow.status=='wait'">等待进行</el-tag>
	  			<el-tag  size="mini" type="warning" v-else-if="flow.status=='run'">正在进行</el-tag>
	  			<el-tag  size="mini" type="success" v-else>已经完成</el-tag>
	    		<span style="padding: 2px 10px;color: black;font-weight: 500;">{{flow.ch_name}}</span>
	  		</el-col>
	  		<el-col :lg="14">
	  			<span style="color:#7a838f;">开始日期</span>
	  			<el-date-picker
	  				:disabled="dateDisabled"
	  				@click="editDate"
			      v-model="flow.begin_date"
			      size="mini"
			      type="date"
			      format="yyyy年MM月dd日"
			      placeholder="选择日期">
			    </el-date-picker>
			    <span style="color:#7a838f;">结束日期</span>
	  			<el-date-picker
	  				:disabled="dateDisabled"
	  				@dblclick="editDate"
			      v-model="flow.end_date"
			      size="mini"
			      type="date"
			      placeholder="选择日期">
			    </el-date-picker>
			    <el-button size="mini" icon="el-icon-edit" v-if="dateDisabled" @click="editDate"></el-button>
			    <el-button size="mini" type="primary" icon="el-icon-check" v-else @click="saveDate"></el-button>
	  		</el-col>
	  		<el-col :lg="3">
	  			<span style="color:#7a838f;">需要工时</span>
  				<span style="font-size: 20px">{{flow.duration}}</span>
  				<span style="color:#7a838f;">天</span>
	  		</el-col>
	  		<el-col :lg="3">
	  			<span style="color:#7a838f;">距离开工</span>
	  			<span style="font-size: 20px">{{flow.to_start}}</span>
  				<span style="color:#7a838f;">天</span>
	  		</el-col>
	  	</el-row>
	  </div>
	  <div class="text item" :hidden="isCollapse">
	    <el-steps :active="actives[index]" finish-status="wait" process-status="finish">
		    <el-step 
		    :title="task.ch_name"  v-for="(task,tindex) in flow.tasks"
		    :key="tindex"
		    @click.native="selectStep(index,tindex)">
			    <template slot="description">
			    	<div style="width: 80px;">
			    		<span>子任务数:</span><span>{{task.subtasks.length}}</span>
			    	</div>
			    	
			    </template>
		    </el-step>
		  </el-steps>

		  <!--任务内容-->
		  <div class="taskInput" v-for="(task,tindex) in flow.tasks" 
		  	:ref="index.toString()+tindex.toString()" 
		  	:hidden="tindex==0 ? false:true">
		  	<div style="margin-bottom: 10px;" v-for="(subtask,index) in task.subtasks" :key="index">
			  	<el-row>
			  		<el-col :span="14">
			  			<el-tag v-if="subtask.status=='wait'" size="mini" type="danger"><i class="el-icon-remove-outline"></i> 未进行</el-tag>
			  			<el-tag v-else-if="subtask.status=='run'" size="mini" type="warning"><i class="el-icon-time"></i> 进行中</el-tag>
			  			<el-tag v-else size="mini" type="success"><i class="el-icon-circle-check"></i> 已完成</el-tag>
			  			<span @click="subTaskDetail(subtask)" style="cursor: pointer;">{{subtask.title}}</span>
			  		</el-col>
			  		<el-col :span="8">
			  			<el-tag type="info" size="small">开始时间: {{formatTime(subtask.begin_date)}}</el-tag>
			  			<el-tag type="info" size="small">截止时间: {{formatTime(subtask.end_date)}}</el-tag>
			  		</el-col>
			  		<el-col :span="2">
			  			<el-dropdown trigger="click">
					      <span class="el-dropdown-link">
					      	<el-tooltip class="item" effect="dark" content="更多" placement="top">
							      <el-button size="mini" style="font-weight: 700;">...</el-button>
							    </el-tooltip>
					      </span>
					      <el-dropdown-menu slot="dropdown">
					        <el-dropdown-item @click.native="startSubTask(subtask)"><i class="fa fa-play-circle primary">开始</i></el-dropdown-item>
					        <el-dropdown-item @click.native="endSubTask(subtask)"><i class="fa fa-stop-circle success">结束</i></el-dropdown-item>
					        <el-dropdown-item @click.native="editSubTask(subtask)"><i class="fa fa-edit primary">编辑</i></el-dropdown-item>
					        <el-dropdown-item @click.native="delSubTask(subtask)"><i class="fa fa-trash-o danger">删除</i></el-dropdown-item>
					      </el-dropdown-menu>
					    </el-dropdown>
			  		</el-col>
			  	</el-row>
			  	<el-divider></el-divider>
		  	</div>
		  	<el-button size="mini" icon="el-icon-plus" @click="addSubTask(task.id)">添加子任务</el-button>
		  </div>
	  </div>
	</el-card>

</div>
</template>
<script>
import {getAPItoken,postAPItoken,putAPItoken,patchAPItoken} from '@/utils/api'
import taskInput from './taskInput'
import taskDetail from './taskDetail'
export default {
	components: {
		taskInput,
		taskDetail
	},
	data () {
		return {
			project_duration: 0,
			subtask_summary: {},
			isCollapse: false,
			project: {},
			action: '添加',
			actives: {}, //存储每个流程下的任务当前激活步骤
			flows: [], // 模版的流程列表
			flowInsts: [], // 流程实例
			taskInputVisible: false,
			taskDetailVisible: false,
			dateDisabled: true,
			descDisabled: true,
			subTaskForm: { // 添加子任务form
				'priority': 'middle',
				'member': []
			},
			currStepID: null,
			isInit: true,
		}
	},
	methods: {
		hiddenStep (index) {
			for(var i in this.flows[index].steps){
				this.$refs[index.toString()+i.toString()][0].style.display='none'
			}
		},
		selectStep (index,tindex) {
			this.actives[index] = tindex
			var temp_actives = this.actives
			this.actives = {}
			this.actives = temp_actives // 重新赋值, 数据更新, vue view才会更新
			this.hiddenStep(index)
			this.$refs[index.toString()+tindex.toString()][0].style.display='block'
		},
		//获取模版流程
    getTempFlows () {
    	const promise = getAPItoken(API.proFlow+'?template='+this.$route.query.template,this.$store.state.user.token)
      promise.then((data)=>{
        this.flows = data
        this.getFlowInsts()
      })
    },
    //获取模版下的指定项目流程实例
    getFlowInsts () {
    	var query_params = '?template='+this.$route.query.template+'&instance='+this.$route.query.project
    	const promise = getAPItoken(API.flowInst+query_params,this.$store.state.user.token)
      promise.then((res)=>{
        if(res.data.length ==0){ // 如果等于0, 说明没有实例化
        	this.flowInsts = this.flows
        }else{ //已经实例化, 获取实例, isInit = false
        	this.flowInsts = res.data
        	for(var i in this.flowInsts){ // 遍历实例
        		this.project_duration += this.flowInsts[i].duration
        		this.actives[i] = 0
	        	this.flowInsts[i]['date_range'] = []
	        	this.flowInsts[i]['date_range'].push(this.flowInsts[i].begin_date) //时间设置成element-ui datepicker需要的list
	        	this.flowInsts[i]['date_range'].push(this.flowInsts[i].end_date)
	        }
	        this.isInit = false
        }
      })
    },
    addSubTask (stepID) {
    	this.action = '添加'
    	this.currStepID = stepID
    	this.taskInputVisible = true
    },
    editSubTask (subtask) {
    	this.subTaskForm = {}
    	this.action = '编辑'
    	this.subTaskForm = subtask
    	this.taskInputVisible = true
    },
    subTaskPatch (subtask,status){
    	var status_dict = {
    		'run':'启动',
    		'finish':'结束'
    	}
    	const promise = patchAPItoken(API.subTask+subtask.id+'/',{'status':status},this.$store.state.user.token)
    	promise.then((res)=>{
    		if(res.status){
    			this.$notify({
	          title: '成功',
	          message: '子任务:'+subtask.title+', '+status_dict[status]+'成功',
	          type: 'success'
	        })
	        this.getFlowInsts()
    		}else{
    			this.$notify({
	          title: '失败',
	          message: res.data,
	          type: 'error'
	        })
    		}
    	})
    },
    startSubTask (subtask) {
    	this.subTaskPatch(subtask,'run')
    },
    endSubTask (subtask) {
    	this.subTaskPatch(subtask,'finish')
    },
    delSubTask (subtask) {

    },
    editDate () {
    	this.dateDisabled = false
    },
    saveDate () {
    	this.dateDisabled = true
    },
    subTaskDetail (subtask) {
    	this.subTaskForm = null
    	this.subTaskForm = subtask
    	this.taskDetailVisible = true
    },
    saveSubTask (subtask) {
    	if(this.action == '添加'){
    		subtask['project'] = this.project.project_name
    		subtask['task'] = this.currStepID
    		var promise = postAPItoken(API.subTask,subtask,this.$store.state.user.token)
    	}else{
    		var promise = putAPItoken(API.subTask+subtask.id+'/',subtask,this.$store.state.user.token)
    	}
    	promise.then((res)=>{
    		if(res.status){
    			this.$notify({
	          title: '成功',
	          message: '子任务'+this.action+'成功',
	          type: 'success'
	        })
	        this.getFlowInsts()
    		}else{
    			this.$notify({
	          title: '失败',
	          message: res.data,
	          type: 'error'
	        })
    		}
    	})
    },
    getDuration (index) {
    	var date= new Date();
    	var to_start = ((this.flows[index].date_range[0] - date)/60/60/1000/24).toFixed(2)
    	this.flows[index].to_start = to_start
    	if(to_start <= 0){
    		this.flows[index].status = 'run'
    	}else{
    		this.flows[index].status = 'wait'
    	}
    	var duration_time = (this.flows[index].date_range[1]-this.flows[index].date_range[0])/60/60/1000/24
    	this.$set(this.flows[index],'duration', duration_time)
    },
    initFlow () {
    	const promise = postAPItoken(API.flowInst,{project:this.project.id,flows:this.flows},this.$store.state.user.token)
    	promise.then((res)=>{
    		if(res.status){
    			this.$notify({
	          title: '成功',
	          message: '项目流程初始化成功',
	          type: 'success'
	        })
	        this.getFlowInsts()
    		}else{
    			this.$notify({
	          title: '失败',
	          message: res.data,
	          type: 'error'
	        })
    		}
    	})
    },
    editFlow () {
    	this.isInit = true
    },
    noEditFlow () {
    	this.isInit = false
    },
    FormatTime(time,fmt){
		  var o = {
	      "M+": time.getMonth() + 1, //月份 
	      "d+": time.getDate(), //日 
	      "H+": time.getHours(), //小时 
	      "m+": time.getMinutes(), //分 
	      "s+": time.getSeconds(), //秒 
	      "q+": Math.floor((time.getMonth() + 3) / 3), //季度 
	      "S": time.getMilliseconds() //毫秒 
		  }
		  if (/(y+)/.test(fmt))
		  	console.log(time.getFullYear())
		  	fmt = fmt.replace(RegExp.$1, (time.getFullYear() + "").substr(4 - RegExp.$1.length))
		  for (var k in o)
		  if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)))
		  return fmt
		},
		formatTime (date_string) {
			if(typeof(date_string) == 'string'){
				var s1 = date_string.replace(/-/g,"/")
				var s2 = s1.replace(/T/g," ")
				var date = new Date(s2)
				return this.FormatTime(date, 'MM月dd日')
			}
			return this.FormatTime(date_string, 'MM月dd日')
		},
		getProject () {
			const promise = getAPItoken(API.instAPI+this.$route.query.project+'/',this.$store.state.user.token)
      promise.then((res)=>{
        if (res.status) {
        	this.project = res.data
        	this.getSubTaskInfo(this.project.project_name)
        }
      })
		},
		collapse () {
			if (this.isCollapse){
				this.isCollapse = false
			} else {
				this.isCollapse = true
			}
		},
		getSubTaskInfo (project_name) {
			//获取项目子任务汇总信息
			var query_params = '?type=subtask&instance='+project_name
			const promise = getAPItoken(API.proInfo+query_params,this.$store.state.user.token)
			promise.then(data=>{
				this.subtask_summary = data
			})
		}
	},
	created () {
		this.getTempFlows()
		this.getProject()
	}
}
</script>
<style scoped>
span{
	font-size: 14px;
}
.el-card {
	margin-bottom: 10px;
}

.taskInput{
	margin-top: 15px;
}

.el-form-item {
  margin-bottom: 12px;
}

</style>